<template lang="pug">
.cp-select-serial-popup
  el-dialog.serial-popup(
    :title="title",
    :visible="visible",
    @close="closeDialog",
    :close-on-click-modal="!isEdit",
    width="560px")
    div(v-show="isEdit")
      p.height32 序列号列表（已选择{{selectList.length}}个，待选择{{quantity}}个）
      el-row(:gutter="16")
        el-col(:span="20")
          el-table.serial-table(
            ref="multipleTable"
            :data="tableList"
            height="398px"
            v-loading="loadingData"
            :row-class-name="rowClass"
            @selection-change="onSelectionChange"
            @row-click="onRowClick"
            border)
            el-table-column(type="selection")
            el-table-column(show-overflow-tooltip, prop="serialNo", label="序列号")
        el-col(:span="4")
          div.btn-wrap
            el-button(plain, @click="resetSelect", v-if="isEdit") 重置
          div.btn-wrap
            el-button(plain, @click="makeSelect", v-if="isEdit") 选择
          div.btn-wrap
            el-button(plain, @click="reverseSelect", v-if="isEdit") 反选
    div(slot="footer")
      el-button(type="primary", plain, @click="closeDialog") 取消
      el-button(type="primary", @click="saveData", v-if="isEdit") 保存
</template>

<script>
import InventoryApi from '@/api/inventory/inbound';

export default {
  name: 'selectserialpopup',
  props: {
    title: String,
    visible: Boolean,
    isEdit: Boolean,
    parentData: Object
  },
  data() {
    return {
      loadingData: false,
      // 表格所有序列号
      tableList: [],
      // 选择的序列号
      selectList: this.parentData.selectList || [],
      // 行选择的序列号
      rowSelect: []
    };
  },
  computed: {
    quantity() {
      let num = 0;
      if (this.parentData.quantity) {
        num = this.parentData.quantity - this.selectList.length;
      }
      return num;
    }
  },
  watch: {
    parentData(newData, oldData) {
      if (newData !== oldData) {
        this.selectList = newData.selectList || [];
        this.getSerial();
      }
    }
  },
  mounted() {
    this.getSerial();
  },
  methods: {
    // 获取序列号
    getSerial() {
      const params = {
        sku: this.parentData.sku,
        storageSite: this.parentData.storageSite,
        batchNo: this.parentData.batchNo,
      };
      this.loadingData = true;
      InventoryApi.getSerial(params).then((res) => {
        this.tableList = res;
        this.loadingData = false;
        // 设置选中
        if (this.$refs.multipleTable) {
          this.selectList.forEach((row) => {
            this.$refs.multipleTable.toggleRowSelection({ serialNo: row }, true);
          });
        }
      }).catch((error) => {
        this.loadingData = false;
        console.log(JSON.stringify(error));
      });
    },
    // 关闭、取消
    closeDialog() {
      this.$emit('close');
    },
    // 保存
    saveData() {
      const data = [];
      this.selectList.forEach((item) => {
        data.push(item.serialNo);
      });
      if (data.length != this.parentData.quantity) {
        this.$message.error('选择数量与所需数量不一致');
        return;
      }
      this.$emit('submit', data);
      this.closeDialog();
    },
    // 选择行的class名
    rowClass({ row }) {
      let name = '';
      this.rowSelect.forEach((item) => {
        if (item.serialNo === row.serialNo) {
          name = 'row-select';
          return name;
        }
      });
      return name;
    },
    // 选择改变时
    onSelectionChange(value) {
      this.selectList = value;
    },
    // 判断rowSelect中是否已存在
    checkRowSelect(row) {
      let has = false;
      this.rowSelect.forEach((item) => {
        if (item.serialNo === row.serialNo) {
          has = true;
          return has;
        }
      });
      return has;
    },
    // 点击某一行时
    onRowClick(row, event) {
      const has = this.checkRowSelect(row);
      if (event.ctrlKey) { // 按住ctrl时选择
        if (has) {
          this.rowSelect = this.rowSelect.filter(item => item.serialNo !== row.serialNo);
        } else {
          this.rowSelect.push(row);
        }
      } else if (event.shiftKey) { // 按住shift时选择
        if (this.startIndex || this.startIndex === 0) { // 开始位置
          if (this.endIndex || this.endIndex === 0) { // 结束位置
            this.startIndex = this.tableList.findIndex(item => item.serialNo === row.serialNo);
            this.endIndex = null;
            this.rowSelect = [];
          } else {
            this.endIndex = this.tableList.findIndex(item => item.serialNo === row.serialNo);
            if (this.startIndex < this.endIndex) { // 按先后顺序
              this.rowSelect = this.tableList.slice(this.startIndex, this.endIndex + 1);
            } else if (this.startIndex > this.endIndex) {
              this.rowSelect = this.tableList.slice(this.endIndex, this.startIndex + 1);
            } else {
              this.rowSelect = [];
            }
          }
        } else {
          this.startIndex = this.tableList.findIndex(item => item.serialNo === row.serialNo);
        }
      } else {
        if (has) {
          this.rowSelect = [];
        } else {
          this.rowSelect = [row];
        }
      }
    },
    // 重置
    resetSelect() {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 选择
    makeSelect() {
      if (this.$refs.multipleTable) {
        this.rowSelect.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
        this.startIndex = null;
        this.endIndex = null;
      }
    },
    // 反选
    reverseSelect() {
      if (this.$refs.multipleTable) {
        this.tableList.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      }
    }
  },
};
</script>

<style lang="sass">
$HEIGHT: 40px
$COLOR: #86c2ff
.cp-select-serial-popup
  .serial-popup
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
    .el-dialog__body
      padding: 16px
    .el-dialog__footer
      padding-top: 0
      text-align: center
      .el-button
        width: 80px
  .height32
    height: 32px
    line-height: 32px
  .el-table
    th, td
      text-align: center
    &.serial-table .cell.el-tooltip
      user-select: none
  .row-select, tr.row-select:hover>td
    background-color: $COLOR
  .btn-wrap
    text-align: center
    padding-top: 16px
</style>
